package com.weds.frame.auth.service;

import com.alibaba.fastjson2.JSON;
import com.weds.frame.auth.mapper.CommMapper;
import com.weds.frame.common.entity.PageSearch;
import com.weds.frame.domain.entity.CommPager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/31 10:17
 */

@Service
public class CommUtil {
    @Autowired
    private CommMapper commMapper;

    /**
     * @Author: Yi
     * @Description 获取表最新主键序列值
     * @Date: 8:28 2018/5/8
     */
    public Integer getKeyNextval(String tableName, String keyName) {
        return commMapper.getKeyNextval(tableName + "_" + keyName + "_seq");
    }

    /**
     * @Author: Yi
     * @Description 获取表当前主键序列值
     * @Date: 8:28 2018/5/8
     */
    public Integer getKeyCurrval(String tableName, String keyName) {
        return commMapper.getKeyCurrval(tableName + "_" + keyName + "_seq");
    }

    /**
     * 功能描述:获取当前实践
     *
     * @param:
     * @return:
     */
    public Timestamp getNowTime() {
        return commMapper.getNowTime();
    }

    public Object setBaseInfo(Object obj) {
        if (getFiledValue(obj, "ctUserId") == null)
            setFiledValue(obj, "ctUserId", 1);
        if (getFiledValue(obj, "ctDate") == null)
            setFiledValue(obj, "ctDate", new Timestamp(System.currentTimeMillis()));
        if (getFiledValue(obj, "ltUserId") == null)
            setFiledValue(obj, "ltUserId", 1);
        setFiledValue(obj, "ltDate", new Timestamp(System.currentTimeMillis()));
        setFiledValue(obj, "useStatusId", 1);
//        setFiledValue(obj, "versionId", versionValue);
        return obj;
    }


    public static void setFiledValue(Object o, String fieldName, Object value) {
        Field f = null;
        try {
            f = o.getClass().getDeclaredField(fieldName);
        } catch (NoSuchFieldException localNoSuchFieldException) {
        }
        if (f == null) {
            return;
        }
        f.setAccessible(true);
        try {
            f.set(o, value);
        } catch (IllegalAccessException localIllegalAccessException) {
        }
    }

    public static Object getFiledValue(Object o, String fieldName) {
        Field f = null;
        try {
            f = o.getClass().getDeclaredField(fieldName);
        } catch (NoSuchFieldException localNoSuchFieldException) {
        }
        if (f == null) {
            return null;
        }
        f.setAccessible(true);
        try {
            return f.get(o);
        } catch (IllegalAccessException localIllegalAccessException) {
        }
        return null;
    }

    public static String getFiledType(Object o, String fieldName) {
        Field f = null;
        try {
            f = o.getClass().getDeclaredField(fieldName);
        } catch (NoSuchFieldException localNoSuchFieldException) {
        }
        if (f == null) {
            return null;
        }
        f.setAccessible(true);
        try {
            if (f.get(o).getClass() == String.class) {
                return "String";
            } else if (f.get(o).getClass() == Integer.class) {
                return "Integer";
            } else if (f.get(o).getClass() == Boolean.class) {
                return "Boolean";
            } else if (f.get(o).getClass() == Timestamp.class) {
                return "Timestamp";
            } else if (f.get(o).getClass() == java.util.Date.class) {
                return "Date";
            }
        } catch (IllegalAccessException localIllegalAccessException) {
        }
        return "Other";
    }

    public static String getClientIp(HttpServletRequest request) {
        if (request == null) {
            return "";
        }
        String clientIp = request.getHeader("x-forwarded-for");
        if (clientIp == null || clientIp.isEmpty() || clientIp.toLowerCase().equals("unknown")) {
            clientIp = request.getRemoteAddr();
        }
        return clientIp;
    }

    public static <T> CommPager<T> commPageSet(PageSearch search, List<T> ls) {
        CommPager<T> re = new CommPager<>();
        re.setPageIndex(search.getPageIndex());
        re.setPageSize(search.getPageSize());
        re.setCurrenRecords(ls.size());
        re.setRecords(ls);
        return re;
    }

    public static <T> CommPager<T> commPageSetWithCount(PageSearch search, List<T> ls, long totalCount) {
        CommPager<T> re = new CommPager<>();
        re.setPageIndex(search.getPageIndex());
        re.setPageSize(search.getPageSize());
        re.setCurrenRecords(ls.size());
        re.setRecords(ls);
        re.setTotalRecord(totalCount);
        re.setTotalPage(Math.toIntExact(totalCount == 0 || search.getPageSize() == 0
                ? 1
                : (totalCount % search.getPageSize() == 0 ? totalCount / search.getPageSize() : (totalCount / search.getPageSize() + 1))));
        return re;
    }

    /**
     * @return boolean
     * @Author fxq
     * @Description 判断list element is all null
     * @Date 15:28 2019/12/16
     * @Param [list]
     **/
    public static boolean isAllNull(Iterable<?> list) {
        for (Object obj : list) {
            if (obj != null)
                return false;
        }

        return true;
    }

    /**
     * @param jexlExp 表达式
     * @param map     参数数据
     * @Author: Yi
     * @Description 执行字符串表达式（参数转换）
     * @Date: 17:38 2020/6/13
     */
//    public static Object convertToCode(String jexlExp, Map<String, Object> map) {
//        //创建或检索引擎
//        JexlEngine jexl = new JexlEngine();
//        //创建一个表达式
//        Expression e = jexl.createExpression(jexlExp);
//        //创建上下文并添加数据
//        JexlContext jc = new MapContext();
//        for (String key : map.keySet()) {
//            jc.set(key, map.get(key));
//        }
//        //现在评估表达式，得到结果
//        if (null == e.evaluate(jc)) {
//            return "";
//        }
//        return e.evaluate(jc);
//    }

    //值比较，null与null相等
    public static Boolean isEqualsIncludeNull(Object a, Object b) {
        if (a != null && b != null)
            return a.equals(b);
        if (a == null && b == null)
            return true;

        return false;
    }

    //多线程负载任务计算
    public static Integer asyncNumber(Integer len, Integer p) {
        Integer avg = len / p;
        Integer rem = len % p;
        return rem > 0 ? (avg + 1) : avg;
    }

    public static void main(String[] args) {
        PageSearch search = new PageSearch();
        search.setPageSize(5);
        search.setPageIndex(2);
        List<Integer> ls = Arrays.asList(new Integer[]{});
        System.out.println("code: " + JSON.toJSONString(commPageSetWithCount(search, ls, 11)));
    }
}
